package com.example.onion.hxchat.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.util.Printer;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.onion.hxchat.util.HttpUtils;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.TestActivity;
import com.example.superyi.mainBar.MainBar;
import com.example.superyi.myteam.R;

import com.example.wjy.MyTeamActivity;
import com.example.wjy.RecommendActivity;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Request;

/**
 * 登录注册界面，环信sdk对于登录状态的判断说是
 * 调用longin成功之后，只要不调用logout，都是属于登录状态
 * <p>
 * 那么可不可能登录一次成功后，借助PassWordHelp保存用户密码，
 * 只要能得到密码就表示状态是登录的（前提就是调用logout必须清除PassWordHelp保存的密码）
 * 还没测试是否按预想进行  尚且这样吧
 *
 * @author:onion
 * @data: 2020/5/19
 */
public class LoginActivity extends AppCompatActivity {

    private EditText mUserNameView;
    private EditText mPasswordView;
    private Button mLoginBtn;
    private Button mSignUpBtn;
    //测试用
    private Button button, button2;

    private Button logoutBtn;

    private CheckBox checkBoxPwd;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};

    private TextView forgetPassword;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
//        logoutBtn = findViewById(R.id.logout_btn);
//        logoutBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                EMClient.getInstance().logout(true);
//            }
//        });


//        button = findViewById(R.id.button);
//        button.setOnClickListener(v -> {
//            Intent intent = new Intent(LoginActivity.this, MyTeamActivity.class);
//            startActivity(intent);
//        });
//
//        button2 = findViewById(R.id.button2);
//        button2.setOnClickListener(v -> {
//            Intent intent = new Intent(LoginActivity.this, RecommendActivity.class);
//            startActivity(intent);
//        });

        initView();
        checkRight();
        //autoLogin();
    }

    private void autoLogin() {
        String number = PassWordHelp.readPassword(LoginActivity.this)[0];
        boolean isLogin = PassWordHelp.readBlob(LoginActivity.this);
        if (isLogin) {
            Intent intent = new Intent(LoginActivity.this, MainBar.class);
            startActivity(intent);
        }
//        if (!("".equals(number))){
//            Intent intent = new Intent(LoginActivity.this,MainActivityWC.class);
//            startActivity(intent);
//        }
    }

    private void checkRight() {
        try { //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        forgetPassword = findViewById(R.id.login_forgotton_password);
        forgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,AlterPassWordActivity.class);
                startActivity(intent);
            }
        });
        mUserNameView = findViewById(R.id.login_username_et);
        mPasswordView = findViewById(R.id.login_password_et);
        mLoginBtn = findViewById(R.id.login_btn);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        mSignUpBtn = findViewById(R.id.sign_up_btn);
        mSignUpBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signUp();
            }
        });
        checkBoxPwd = findViewById(R.id.login_remember_pwd);
        String account = PassWordHelp.readPassword(LoginActivity.this)[0];
        String pwd = PassWordHelp.readPassword(LoginActivity.this)[1];
        boolean isRemember = PassWordHelp.readBlob(this);
        if (isRemember) {
            mUserNameView.setText(account);
            mPasswordView.setText(pwd);
        }
        checkBoxPwd.setChecked(isRemember);
    }


    /**
     * 注册方法
     */
    private void signUp() {
        String number = mUserNameView.getText().toString().trim();//用户id
        String password = mPasswordView.getText().toString().trim();//用户密码
        Log.e("Login", "number" + number);
        Log.e("Login", "password" + password);
        if (!("".equals(number)) && !("".equals(password))) {
            Log.e("zhuce", "注册");
            //EMClient.getInstance().createAccount(number, password);
            HttpUtils httpUtils = HttpUtils.getInstance();
            FormBody.Builder builder = new FormBody.Builder();
            builder.add("userId", number);
            builder.add("userPwd", password);
            FormBody formBody = builder.build();
            httpUtils.asyncPost("http://49.232.60.155:8080/AppServer_war/RegisterServlet", formBody, new HttpUtils.HttpCallBack() {
                @Override
                public void onError(Request request, IOException e) {

                }

                @Override
                public void onSuccess(Request request, String result) {
                    Gson gson = new Gson();
                    JsonObject resultJson = gson.fromJson(result, JsonObject.class);
                    JsonElement jsonElement = resultJson.get("state");
                    Log.e("login Result ",resultJson.toString());
                    if (jsonElement.getAsString().equals("success")) {
                        Log.e("application", "注册成功");
                        showToast(LoginActivity.this,"注册成功");
                        login();
                    } else {
                        showToast(LoginActivity.this,"注册失败，用户已存在或网络问题！");
                        Log.e("application", "注册失败");
                    }
                }
            });
        } else {
            Toast.makeText(LoginActivity.this, "账户或密码为空，注册失败!", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 显示toast
     * @param ctx
     * @param msg
     */
    public static void showToast(final Activity ctx, final String msg) {
        // 判断是在子线程，还是主线程
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
        } else {
            // 子线程
            ctx.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
                }
            });
        }
    }

        /**
         * 登录方法
         */
    private void login() {
        String number = mUserNameView.getText().toString().trim();//用户id
        String password = mPasswordView.getText().toString().trim();//用户密码
        boolean isSelect = checkBoxPwd.isChecked();
        Log.d("id", number);
        Log.d("pwd", password);
        Log.d("isSelect", String.valueOf(isSelect));
        EMClient.getInstance().login(number, password, new EMCallBack() {
            @Override
            public void onSuccess() {
                PassWordHelp.savePassword(LoginActivity.this, number, password, isSelect);
                startActivity(new Intent(LoginActivity.this, MainBar.class));
                finish();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("application", "登录失败" + s);
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }
}
